package com.cn.algorithm.two.line.test;

import java.util.Arrays;

public class HeapSortJ {
    public static void main(String[] args) {
        int[] arr = {9, 7, 4, 2, 5, 3, 8};
        sort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void sort(int[] arr) {
        if (arr == null || arr.length <= 1) {
            return;
        }
        for (int i = arr.length / 2 - 1; i >= 0; i--) {
            siftDown(arr, 0, arr.length);
        }
        for (int i = arr.length - 1; i > 0; i--) {
            swap(arr, 0, i);
            siftDown(arr, 0, i);
        }
    }

    public static void siftDown(int[] arr, int i, int length) {
        int tmp = arr[i];
        for (int j = i * 2 + 1; j < length; j = j * 2 + 1) {
            if ((j + 1) < length && arr[j] < arr[j + 1]) {
                j++;
            }
            if (arr[j] > tmp) {
                arr[i] = arr[j];
                i = j;
            }
        }
        arr[i] = tmp;
    }

    public static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}
